import java.util.Arrays;
import java.util.HashMap;

public class TestHeap {

    public int[]elem;
    public int usedSize;
    public TestHeap(){
        elem=new int[10];
    }

    public void createHeap(int[]array){
        for (int i = 0; i < array.length; i++) {
            elem[i]=array[i];
            usedSize++;
        }
        for (int parent = (usedSize-1-1)/2; parent >=0 ; parent--) {
            shiftDown(parent,usedSize);
        }
    }

    public void shiftDown(int parent,int len) {
        int child = 2 * parent + 1;
        while (child < len) {
            if (child + 1 < len && elem[child + 1] > elem[child])
                child++;
            if (elem[parent] <elem[child]) {
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                parent=child;
                child=2*parent+1;
            } else {
                break;
            }
        }
    }

    public void HeapSort(){
        int end=usedSize-1;
        while(end>0){
            int tmp=elem[0];
            elem[0]=elem[end];
            elem[end]=tmp;
            shiftDown(0,end);
            end--;
        }
    }



    public void offer(int val){
        if(isFull()){
            elem= Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize]=val;
        usedSize++;
        shiftUp(usedSize-1);
    }

    public void shiftUp(int child){
        int parent=(child-1)/2;
        while(child>0){
            if(elem[parent]<elem[child]){
                int tmp=elem[child];
                elem[child]=elem[parent];
                elem[parent]=tmp;
                child=parent;
                parent=(child-1)/2;
            }else{
                break;
            }
        }
    }
    public boolean isFull(){
        return usedSize==elem.length;
    }

    public int poll(){
        if(isEmpty()){
            throw new RuntimeException("优先级队列为空");
        }
        int tmp=elem[0];
        elem[0]=elem[usedSize-1];
        elem[usedSize-1]=tmp;
        usedSize--;
        shiftDown(0,usedSize);

        return tmp;
    }
    public boolean isEmpty(){
        return usedSize==0;
    }

    public static void main(String[] args) {
        int[]array={4,55,3,66,7,33,54,22,1};
        TestHeap testHeap=new TestHeap();
        testHeap.createHeap(array);
        System.out.println("===");
        testHeap.offer(99);
        System.out.println("---");
        //testHeap.HeapSort();
        System.out.println(testHeap.poll());
        System.out.println(testHeap.poll());
        System.out.println("---");
    }
}

